#include "widget.h"
#include "ui_widget.h"
#include <QSerialPortInfo>
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    QStringList serialNamePort;
    serilaPort = new QSerialPort(this);

    connect(serilaPort,SIGNAL(readyRead()),this,SLOT(serialport_readready_slot()));

    foreach(const QSerialPortInfo&info ,QSerialPortInfo::availablePorts())
    {// 遍历返回串口号信息
        serialNamePort<<info.portName();
    }
    ui->seialCb->addItems(serialNamePort);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::serialport_readready_slot()
{
    QString buf;// 定义一个QString类型的buf
    buf = QString(serilaPort->readAll());// 把读取到的数据强制类型转换并写入buf
    ui->recvEdit->appendPlainText(buf);// 在接受栏中显示数据
}

void Widget::on_openBt_clicked()
{
    QSerialPort::BaudRate bauRate; //波特率,::作用域符号，避免不同的类有名称相同的成员
    QSerialPort::DataBits dataBits; //数据位
    QSerialPort::StopBits stopBits; //停止位
    QSerialPort::Parity checkBits; //校验位

// 设置波特率
    if(ui->baundrateCb->currentText() == "4800")
    {
        bauRate = QSerialPort::Baud4800;
    }
    else if(ui->baundrateCb->currentText() == "9600")
    {
        bauRate = QSerialPort::Baud9600;
    }
    else if(ui->baundrateCb->currentText() == "115200")
    {
        bauRate = QSerialPort::Baud115200;
    }

// 设置数据位
    if(ui->dateCb->currentText() == "5")
    {
        dataBits = QSerialPort::Data5;
    }
    else if(ui->dateCb->currentText() == "6")
    {
        dataBits = QSerialPort::Data6;
    }
    else if(ui->dateCb->currentText() == "7")
    {
        dataBits = QSerialPort::Data7;
    }
    else if(ui->dateCb->currentText() == "8")
    {
        dataBits = QSerialPort::Data8;
    }

// 设置停止位
    if(ui->stopCb->currentText() == "1")
    {
        stopBits = QSerialPort::OneStop;
    }
    else if(ui->stopCb->currentText() == "1.5")
    {
        stopBits = QSerialPort::OneAndHalfStop;
    }
    else if(ui->stopCb->currentText() == "2")
    {
        stopBits = QSerialPort::TwoStop;
    }

// 设置校验位
    if(ui->checkCb->currentText() == "none")
    {
        checkBits = QSerialPort::NoParity;
    }


    serilaPort->setPortName(ui->seialCb->currentText());
    serilaPort->setBaudRate(bauRate);
    serilaPort->setDataBits(dataBits);
    serilaPort->setStopBits(stopBits);
    serilaPort->setParity(checkBits);


    if(serilaPort->open(QIODevice::ReadWrite) == true)
    {
        QMessageBox::information(this,"提示","成功");
    }
    else
    {
        QMessageBox::critical(this,"提示","失败");
    }

}

void Widget::on_closeBt_clicked()
{
    serilaPort->close();
}

void Widget::on_sendBt_clicked()
{
    serilaPort->write(ui->sendEdit->text().toLocal8Bit().data());
}

void Widget::on_removeBt_clicked()
{
    ui->recvEdit->clear();
}
